package cn.lwx.javaweb.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 拦截器
 *
 * @author lwx
 * @date 2022-05-26
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取请求路径
        String servletPath = request.getServletPath();

        HttpSession session = request.getSession(false);

        // 放行的路径
        if("/index.jsp".equals(servletPath) || "/register.jsp".equals(servletPath) ||
                "/login.jsp".equals(servletPath) || "/404.jsp".equals(servletPath) ||
                "/avoid/login".equals(servletPath) || "/login".equals(servletPath) ||
                "/exit".equals(servletPath) || servletPath.contains(".css") ||
                servletPath.contains(".jpg") || servletPath.contains(".gif") ||
                (session != null && session.getAttribute("user") != null)){

            filterChain.doFilter(request, response);
        }else{
            // 拦截后要跳转的页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
